import { defineConfig,ConfigEnv, loadEnv } from 'vite'
import pkg from './package.json'
import dayjs from 'dayjs'
import { wrapperEnv } from './build/utils'
import { createProxy } from './build/vite/proxy'
import { createBuild } from './build/vite/build'
import { createVitePlugins } from './build/vite/plugin'
import { fileURLToPath } from 'url' //解决项目初始化已经配置好了一个 src 别名

//import path from "path" 注意:在ts模块中加载node 核心模块需要安装 node 的类型补充模块:npm i @type/node -D
import path from "path"
const resolve = (dir:string) => path.join(__dirname,dir)

const { dependencies, devDependencies, name, version } = pkg

//应用信息
const __APP_INFO__ = {
  pkg:{ dependencies, devDependencies, name, version },
  lastBuildTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
}

// https://vitejs.dev/config/
export default defineConfig(({command,mode}: ConfigEnv) => {
  const root = process.cwd() //当前工作目录--共享配置:项目根目录（index.html 文件所在的位置
  console.log('共享配置',root)
  const isBuild = command === 'build' //是否是构建serve
  console.log('vite.config.ts文件中的isBuild', isBuild)

  const env = loadEnv(mode, root) //加载env环境
  const viteEnv = wrapperEnv(env)
  console.log('viteEnv', viteEnv)
  const { VITE_PUBLIC_PATH, VITE_OUTPUT_DIR } = viteEnv

  return {
    base: VITE_PUBLIC_PATH, //打包路径
    root,
    plugins:createVitePlugins(viteEnv, isBuild) ,
    resolve:{
      alias:{
        //'@':resolve("src")
        '@': fileURLToPath(new URL("./src", import.meta.url)),
        'mock': fileURLToPath(new URL("./mock", import.meta.url))
      }
    },
    css:{
      preprocessorOptions:{
        scss:{
          charset:false,//避免出现：build时 @charset必须在第一行警告
          additionalData: `
            @import "@/styles/mixin.scss";
            @import "@/styles/variables.scss";
          `
        }
      }
    },
    server:{
      host:true,
      open:true,
      proxy:createProxy()
    },
    build:createBuild(viteEnv),
    define: {
      __APP_INFO__: JSON.stringify(__APP_INFO__)
    }
  }
})

